package com.future.mayi.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.app.App;
import com.future.mayi.model.AreaModel;
import com.future.mayi.model.CityModel;
import com.future.mayi.qsale.model.QsaleGoodsListModel;
import com.future.mayi.response.AddressResponse;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.future.mayi.R;
import com.future.mayi.model.AddressModel;
import com.future.mayi.model.ProvinceModel;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class AddAddressActivity extends BaseTitleActivity {
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.edt_phone)
    EditText edtPhone;
    @BindView(R.id.tv_select_address)
    TextView tvSelectAddress;
    @BindView(R.id.edt_other)
    EditText edtOther;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.tv_default)
    TextView tvDefault;


    private AddressModel model;
    private int position = -1;

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("收货地址");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_add_address);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            model = (AddressModel) getIntent().getSerializableExtra("model");
            position = getIntent().getIntExtra("position", -1);
        }
        if (model == null) model = new AddressModel();
        else {
            edtName.setText(model.getName());
            tvSelectAddress.setText(model.getLocation());
            edtPhone.setText(model.getPhone());
            edtOther.setText(model.getDetail());
        }


        Drawable drawable = mContext.getResources().getDrawable(R.drawable.img_select_f);
        if (model.getIsdefault() == 1) {
            drawable = mContext.getResources().getDrawable(R.drawable.img_select_t);
            tvDefault.setTag(1);
        } else tvDefault.setTag(0);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tvDefault.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    protected void initDates() {
        readCityList();
    }

    @Override
    protected void initListener() {

    }


    public void enter() {

        if (TextUtils.isEmpty(edtName.getText())) {
            toast("请填写姓名");
            return;
        }
        model.setName(edtName.getText().toString());

        if (TextUtils.isEmpty(edtPhone.getText())) {
            toast("请填写手机号");
            return;
        }
        model.setPhone(edtPhone.getText().toString());

        if (TextUtils.isEmpty(model.getLocation())) {
            toast("请选择城市");
            return;
        }

        if (TextUtils.isEmpty(edtOther.getText())) {
            toast("请填写详细地址");
            return;
        }
        model.setDetail(edtOther.getText().toString());
        model.setIsdefault((int) tvDefault.getTag());
        Intent intent = new Intent();
        intent.putExtra("model", model);
        intent.putExtra("position", position);
        setResult(Activity.RESULT_OK, intent);
        CommonUtils.hideKeyboard(null, this);
        finish();
    }


    @OnClick({R.id.tv_select_address, R.id.tv_enter, R.id.tv_default})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select_address:
                CommonUtils.hideKeyboard(null, this);
                if (addressView != null) {
                    addressView.show();
                }
                break;
            case R.id.tv_enter:
                enter();
                break;
            case R.id.tv_default:
                Drawable drawable = mContext.getResources().getDrawable(R.drawable.img_select_f);
                if (((int) tvDefault.getTag()) == 0) {
                    drawable = mContext.getResources().getDrawable(R.drawable.img_select_t);
                    tvDefault.setTag(1);
                } else tvDefault.setTag(0);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                tvDefault.setCompoundDrawables(drawable, null, null, null);
                break;
        }
    }

    private OptionsPickerView addressView;

    //城市初始化
    public void readCityList() {
        String result = (String) SharedPreferencesUtils.get(mContext, SharedPreferencesUtils.SpEnum.City, "");
        if (!TextUtils.isEmpty(result)) {
            parseCity(result);
            return;
        }
        getCityData();
    }

    private void getCityData() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.getCityCommon)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        dissmissLoadingDialog();
                        SharedPreferencesUtils.set(mContext, SharedPreferencesUtils.SpEnum.City, response.content);
                        parseCity(response.content);
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new DefaultResponse());
    }

    private ArrayList<String> provinceList;
    private ArrayList<List<String>> cityList;
    private ArrayList<List<List<String>>> areaList;

    public void parseCity(String json) {
        if (TextUtils.isEmpty(json)) {
            toast("城市数据加载失败");
            return;
        }
        List<ProvinceModel> list = App.getGson().fromJson(json, new TypeToken<List<ProvinceModel>>() {
        }.getType());
        provinceList = new ArrayList<>();
        cityList = new ArrayList<>();
        areaList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ProvinceModel provinceModel = list.get(i);
            provinceList.add(provinceModel.getName());
            List<CityModel>  provinceCityList = provinceModel.getCity();
            List<String> cityName = new ArrayList<>();
            List<List<String>> area = new ArrayList<>();
            for (int j = 0; j < provinceCityList.size(); j++) {
                cityName.add(provinceCityList.get(j).getName());
                area.add(provinceCityList.get(j).getArea());
            }
            cityList.add(cityName);
            areaList.add(area);
        }
        if (addressView==null){
            addressView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    String province = provinceList.get(options1);
                    String city = cityList.get(options1).get(options2);
                    String area = areaList.get(options1).get(options2).get(options3);
                    String address = province + "-" + city + "-" + area;
                    AreaModel areaModel = new AreaModel();
                    areaModel.setProvince(province);
                    areaModel.setCity(city);
                    areaModel.setRegion(area);
                    model.setLocation(address);
                    model.setArea(areaModel);
                    tvSelectAddress.setText(address);
                }
            })
                    .setCancelColor(getResources().getColor(R.color.main_text_color))
                    .setSubmitColor(getResources().getColor(R.color.main_color))
                    .setContentTextSize(20)
                    .build();
        }
        addressView.setPicker(provinceList, cityList, areaList);
    }
}
